<#
.SYNOPSIS
启动学生管理系统并验证其功能

.DESCRIPTION
此脚本将启动Docker Compose来运行学生管理系统的所有服务，包括MySQL数据库、后端API和前端应用程序，并进行简单的验证。

.NOTES
运行此脚本需要安装Docker和Docker Compose
#>

# 确保以管理员权限运行
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator"))
{
    Write-Warning "请以管理员权限运行此脚本！"
    Exit
}

# 检查Docker是否已安装
Write-Host "正在检查Docker是否已安装..."
if (-not (Get-Command "docker" -ErrorAction SilentlyContinue))
{
    Write-Error "未找到Docker。请先安装Docker Desktop for Windows，然后重新运行此脚本。"
    Exit
}

# 检查Docker是否正在运行
Write-Host "正在检查Docker是否正在运行..."
try {
    docker info > $null
} catch {
    Write-Error "Docker未运行。请先启动Docker Desktop，然后重新运行此脚本。"
    Exit
}

# 定义变量
$dockerComposeFile = Join-Path -Path $PSScriptRoot -ChildPath "docker\docker-compose.yml"
$envFile = Join-Path -Path $PSScriptRoot -ChildPath "docker\.env"

# 检查.env文件是否存在，如果不存在则创建一个
if (-not (Test-Path $envFile)) {
    Write-Host ".env文件不存在，正在创建..."
    Copy-Item "$PSScriptRoot\docker\.env.example" $envFile
    Write-Host "已创建.env文件，请根据需要进行编辑。"
}

# 启动Docker Compose服务
Write-Host "正在启动学生管理系统服务..."
docker-compose -f $dockerComposeFile --env-file $envFile up -d

if ($LASTEXITCODE -ne 0) {
    Write-Error "Docker Compose启动失败，请检查错误信息。"
    Exit
}

# 等待服务启动
Write-Host "等待服务启动..."
Start-Sleep -Seconds 30

# 验证MySQL数据库
Write-Host "正在验证MySQL数据库..."
docker exec -it student-management-db mysql -u admin -p123456 -e "USE StudentManagementDB; SHOW TABLES;" StudentManagementDB

if ($LASTEXITCODE -ne 0) {
    Write-Warning "MySQL数据库验证失败，可能是服务尚未完全启动，请稍后再试。"
} else {
    Write-Host "MySQL数据库验证成功！"
}

# 验证后端API
Write-Host "正在验证后端API..."
try {
    $apiUrl = "http://localhost:5000/swagger/index.html"
    $response = Invoke-WebRequest -Uri $apiUrl -UseBasicParsing -TimeoutSec 10
    Write-Host "后端API验证成功！您可以通过以下URL访问API文档：$apiUrl"
} catch {
    Write-Warning "后端API验证失败，可能是服务尚未完全启动，请稍后再试。"
}

# 验证前端应用
Write-Host "正在验证前端应用..."
try {
    $frontendUrl = "http://localhost:80"
    $response = Invoke-WebRequest -Uri $frontendUrl -UseBasicParsing -TimeoutSec 10
    Write-Host "前端应用验证成功！您可以通过以下URL访问前端应用：$frontendUrl"
} catch {
    Write-Warning "前端应用验证失败，可能是服务尚未完全启动，请稍后再试。"
}

# 显示登录信息
Write-Host ""
Write-Host "系统已启动，您可以使用以下默认账号登录："
Write-Host "- 管理员账号: admin / Admin@123"
Write-Host "- 教师账号: teacher / Teacher@123"
Write-Host "- 学生账号: student / Student@123"

Write-Host ""
Write-Host "如果需要停止系统，请运行以下命令："
Write-Host "docker-compose -f $dockerComposeFile --env-file $envFile down"

Write-Host ""
Write-Host "祝您使用愉快！"